/* global console,process */
import { copyFileSync, existsSync, promises as fsPromises } from 'fs';
import { exec } from 'child_process';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import readline from 'readline';

// 将 exec 函数转换为返回 Promise 的函数，以便使用 async/await
const execPromise = (command) => {
  return new Promise((resolve, reject) => {
    exec(command, (error, stdout, stderr) => {
      if (error) {
        console.error(`执行错误: ${stderr}`);
        reject(error);
      }
      resolve(stdout);
    });
  });
};

// 封装一个交互输入函数
function ask(question) {
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
  return new Promise((resolve) => rl.question(question, (ans) => {
    rl.close();
    resolve(ans.trim());
  }));
}

async function main() {
  try {
    // 步骤 1: 构建项目
    console.log('正在构建项目...');
    await execPromise('npm run build');
    console.log('构建完成。');
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = dirname(__filename);

    const filesToCopy = ['package.json', 'LICENSE', 'README.md'];
    const distDir = join(__dirname, 'dist');

    // 确保 dist 目录存在
    await fsPromises.mkdir(distDir, { recursive: true });

    // 步骤 2: 同步复制文件
    console.log('正在将必要文件复制到 dist...');
    for (const file of filesToCopy) {
      const srcPath = join(__dirname, file);
      const destPath = join(distDir, file);
      if (existsSync(srcPath)) {
        copyFileSync(srcPath, destPath);
      } else {
        console.warn(`警告: ${file} 不存在。`);
      }
    }
    console.log('复制完成。');

    // console.log('正在切换npm镜像...');
    // await execPromise('npm config set registry https://registry.npmjs.org/');
    // console.log('npm镜像切换成功。');

    // 更改工作目录到 dist
    process.chdir(distDir);
    // 当前目录
    console.log('当前目录:', process.cwd());

    // 步骤 3: 从 dist 发布
    // 如果命令行没传，就交互式输入 OTP
    let otp = process.argv.slice(2).find(arg => arg.startsWith('--otp='))?.split('=')[1];
    if (!otp) {
      otp = await ask('请输入 OTP: ');
    }

    if (!otp) {
      throw new Error('未提供 OTP，发布已中止。');
    }
    console.log('正在发布包...');
    await execPromise(`npm publish --otp=${otp}`);
    console.log('包发布成功。');

    console.log('正在切换 npm 阿里云镜像...');
    await execPromise('npm config set registry https://registry.npmmirror.com/');
    console.log('阿里云镜像切换成功。');
  } catch (error) {
    console.error('发布过程中发生错误:', error);
  }
}

main();
